var cid = 1;var todoTimer;
var clockTime = 600; //计时60s
var seriesObject = new Object(), tabId= '';;
var arr = new Array(), colorList = new Array();
colorList.push("#546FC6");
colorList.push("#FBB141");
colorList.push("#86B96F");
colorList.push("#67B47F");
colorList.push("#FDC937");
colorList.push("#FD7E56");
colorList.push("#ABBF56");
colorList.push("#F6963E");
colorList.push("#66A281");
colorList.push("#D34F51");
colorList.push("#61A52C");
colorList.push("#A998B0");
colorList.push("#6B907F");
colorList.push("#5E87BB");
colorList.push("#A37A6B");
colorList.push("#9C9B9D");
var inventoryTypeObj = convertEnumToObj(inventoryTypeList);
layui.use(['table', 'table', 'form', 'laydate'], function() {
	var table = layui.table, $ = layui.jquery, layer = layui.layer,
		element = layui.element, form = layui.form, laydate = layui.laydate;
	//初始化查询参数
	loadData({});
	setTimeout(function () {
		loadWaring({orgId:$('.search-origin').val()}, '/material-history/waring');
	}, 500);
	refreshTimer(clockTime);
	laydate.render({
		elem: '#search-time',
		type: 'datetime',
		done: function(value, date, endDate){
			// console.log(value); // 日期字符，如： 2017-08-18
			// console.log(date); // 包含年月日时分秒各项值的对象
			// console.log(endDate); // 结束日期时间对象，当设置 range 时才会返回。对象成员同上。
		}
	});
	$('.stock-tab-title').on('click', "li", function(title) {
		var id = $(this).attr('data-id');
		if (!isNull(id)) {
			tabId = arr[id];
			$("#" + arr[id]).show();
		}
	});
	$('.stock-content').on('click', '.update-store-btn', function () {//点击更正库存
		var storeName = $(this).attr('data-storeName');
		var lineName = $(this).attr('data-lineName');
		var storeValue = $(this).attr('data-storeValue');
		var storeId = $(this).attr('data-id');
		var maxCapacity = $(this).attr('data-maxCapacity');
		var nameNorms = $(this).attr('data-nameNorms');
		var showText = "材料:" + nameNorms + ",现有库存:" + storeValue + "吨,最大容量:" + maxCapacity + "吨";
		layer.open({
			type: 1,
			area: '400px',
			resize: false,
			shadeClose: true,
			title: lineName + '-->' + storeName + ' 库存盘点校正',
			content: '<div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">\n' +
				'<div class="demo-login-container">\n' +
				'<div class="layui-form-item">\n' +
				'<div class="layui-input-wrap">\n' +
				'<input type="text" value="' + showText + '" readonly placeholder="原库存量(吨)" lay-reqtext="原库存量(吨)" autocomplete="off" class="layui-input" lay-affix="clear">\n' +
				'</div></div>\n' +
				'<div class="layui-form-item">\n' +
				'<div class="layui-input-wrap">\n' +
				'<div class="layui-input-prefix"></div>\n' +
				'<input value="0" placeholder="请填写校正后的库存量(吨)" lay-reqtext="请填写校正后的库存量(吨)" autocomplete="off" class="layui-input update-storeValue">\n' +
				'</div></div>\n' +
				'<div class="layui-form-item">\n' +
				'<a href="javascript:void(0)" data-storeValue="' + storeValue + '" data-maxCapacity="' + maxCapacity
				+ '" data-id="' + storeId + '" class="layui-btn layui-btn-fluid save-store">保存盘存数据</a>\n' +
				'</div></div></div>'
		})
	});
	$('body').on('click', '.save-store', function () {
		var storeValue = $('.layui-layer-content').find('.update-storeValue').val();
		var maxCapacity = $(this).attr('data-maxCapacity');
		var id = $(this).attr('data-id');
		var isInsert = $('.isInsert').val();
		var oldStoreValue = $(this).attr('data-storeValue');
		// console.log(storeValue + '   ' + oldStoreValue + '   ' + maxCapacity)
		if (isInsert != 1) {
			layer.msg('您没有校正数据权限');
			return;
		}
		if (id == null ) {
			layer.msg('仓位信息错误,请刷新重试~！');
			return ;
		}
		if (maxCapacity == null ) {
			layer.msg('仓位最大容量错误,请刷新重试~！');
			return ;
		}
		if (storeValue == null) {
			layer.msg('请输入校正后的库存,且不能小于0~！');
			return ;
		}
		if (parseFloat(storeValue) > parseFloat(maxCapacity)) {
			layer.msg('请校正后的库存不能大于最大容量' + maxCapacity + '~！');
			return ;
		}
		layer.confirm('是否将原库存量' + oldStoreValue + '吨调整为新库存' + storeValue + '吨吗？', {
			btn: ['确定', '取消']
		}, function(index, layero){
			storeValue = storeValue * 1000;
			oldStoreValue = oldStoreValue * 1000;
			var option = {storageId:id,storeValue:storeValue,initial:oldStoreValue};
			save(option, "/material-history/update-dosage");
			// layer.close(index);
			layer.closeAll();
		});
	});
	$('.store-save-item').on('click', function () {//更新库存
		var storeValue = $('.add-newStoreValue').val();
		var maxCapacity = $('.add-maxCapacity').val();
		var id = $('.add-storeId').val();
		var isInsert = $('.isInsert').val();
		var oldStoreValue = $('.add-storeValue').val();
		// console.log(storeValue + '   ' + oldStoreValue + '   ' + maxCapacity)
		if (isInsert != 1) {
			layer.msg('您没有校正数据权限');
			return;
		}
		if (id == null ) {
			layer.msg('仓位信息错误,请刷新重试~！');
			return ;
		}
		if (maxCapacity == null ) {
			layer.msg('仓位最大容量错误,请刷新重试~！');
			return ;
		}
		if (storeValue == null) {
			layer.msg('请输入校正后的库存,且不能小于0~！');
			return ;
		}
		if (parseFloat(storeValue) > parseFloat(maxCapacity)) {
			layer.msg('请校正后的库存不能大于最大容量' + maxCapacity + '~！');
			return ;
		}
		layer.confirm('是否将原库存量' + oldStoreValue + '吨调整为新库存' + storeValue + '吨吗？', {
			btn: ['确定', '取消']
		}, function(index, layero){
			storeValue = storeValue * 1000;
			oldStoreValue = oldStoreValue * 1000;
			var option = {storageId:id,storeValue:storeValue,initial:oldStoreValue};
			save(option, "/material-history/update-dosage");
			// layer.close(index);
			layer.closeAll();
		});
	});
	$(document).keyup(function(event){
		if(event.keyCode ==13){
			$(".search-btn").trigger("click");
		}
	});

	$(".addModal .close").on("click", function() {
		$(".addModal").hide();
		$(".addModal input").val("");
		$(".addModal select").val("");
		$(".addModal textarea").val("");
		form.render();
	});
	$(".search-btn").on("click", function() {
		var time = $('.search-time').val();
		var options = { };
		if (!isNull(time))
			options['time'] = time;
		loadData(options);
	});
	function loadWaring(option, url) {//未盘存预警
		$.ajax({
			url: url,
			type: 'post',
			dataType: 'json',
			data:option,
			timeout: 30000,
			success: function(res) {
				// console.log(res)
				if(res.code == 0 && res.data != null) {
					var data = res.data;
					var tip = '';
					$.each(data, function (i, v) {
						tip += '仓位:' + v.storeName + ',材料' + v.materialNorms
							+ ',超过' + v.unInventoryDay + '天未盘存</br>';
					});
					if (tip != '') {
						layer.alert(tip, {
							icon: 0,
							shadeClose: true,
							title: '仓位材料未盘存预警!!!'});
					}
				} else {
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					return;
				}
			}
		})
	}

	function save(option, url) {//新增或修改
		var loading = layer.load(1);
		$.ajax({
			url: url,
			type: 'post',
			dataType: 'json',
			data:option,
			timeout: 30000,
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					layer.msg("更新成功!");
					$('.add-storeId').val('-1');
					setTimeout(function () {
						$('.addModal').hide();
						$(".addModal input").val("");
						$(".addModal select").val("");
						$(".addModal textarea").val("");
						form.render();
					});
					$(".search-btn").trigger("click");
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}
			}
		})
	}
	//获取数据列表
	function loadData(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/material-history/real-time",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				console.log(res);
				if(res.code == 0) {
					//具体数据列表
					var data = res.data;
					if(data == null || data.length <= 0) {
						$(".clientList .tableList").empty().append("<tr><td colspan='7'>暂无数据</td></tr>");
						return;
					}
					var html = '';
					var ele = 'main';
					var stockHtml = '';
					var tStockHtml = '';//筒仓明细
					var gStockHtml = '';//共享仓明细
					var dStockHtml = '';//堆仓明细
					var tabTitleHtml = '';
					var idx = 0;
					var detailList = new Array();
					var chartList = new Array();
					$.each(data, function(index, val) {
						var id = ele + idx;
						if (index.indexOf('明细') == -1) {
							stockHtml += '<div class="layui-tab-item layui-show stock-main"><div class="main-i viewimg">' +
								'<div id="' + id + '" class="charts-main" style="height: 750px"></div>' +
								'</div></div>';
						}

						if (idx == 0) {
							tabId = id;
							tabTitleHtml += '<li class="layui-this" data-id="' + idx + '">' + index + '</li>';
						}else {
							tabTitleHtml += '<li data-id="' + idx + '">' + index + '</li>';
						}
						arr[idx] = id;

						idx++;
						var xAxisArray = new Array();
						var seriesArray = new Array();
						var yMaxArray = new Array();
						$.each(val, function (i, v) {
							var showName = v.name + '\n' + v.nameNorms;
							if (index == '堆仓')
								showName = v.nameNorms;
							// if (index == '共享仓')
							// 	showName = v.nameNorms;
							seriesObject[showName] = v;
							xAxisArray.push(showName);
							var maxCapacity =v.maxCapacity;
							if (maxCapacity < 0)
								maxCapacity = 300;
							else
								maxCapacity = maxCapacity / 1000;
							var yMaxObj = {type: "value", max: maxCapacity};
							yMaxArray.push(yMaxObj);
							var color = '';
							if (i < colorList.length)
								color = colorList[i];
							else
								color = colorList[colorList.length % i];
							var itemObj = {itemStyle:{color:color},value:v.storeValue};
							seriesArray.push(itemObj);
							var netWeight = 0;
							var realExpend = 0;
							if (v.netWeight != null)
								netWeight = parseFloat(v.netWeight / 1000).toFixed(1);
							if (v.realExpend != null)
								realExpend = parseFloat(v.realExpend / 1000).toFixed(1);
							var rate = (parseFloat(v.storeValue) / parseFloat(maxCapacity)) * 100;
							var inventoryType = '';
							var startDate = convertVal(v.startDate);
							var initial = 0;
							var adjustment = 0;
							var lineName = v.lineName;
							if (index == '共享仓' || index == '堆仓')
								lineName = index;
							if (v.adjustment != 0)
								adjustment = parseFloat(v.adjustment / 1000).toFixed(1);
							if (v.initial != 0)
								initial = parseFloat(v.initial / 1000).toFixed(1);
							if (v.historyType != null)
								inventoryType = inventoryTypeObj[v.historyType];
							var btn = '<a data-nameNorms="' + v.nameNorms + '" data-maxCapacity="' + maxCapacity + '" data-lineName="' + lineName + '" data-storeName="' + v.name
								+ '" data-storeValue="' + v.storeValue + '" data-id="' + v.id
								+ '" href="javascript:void(0)" class="layui-btn layui-btn-xs update-store-btn">更正库存</a>';
							if (index == '筒仓明细') {
								tStockHtml += "<tr><td>" + lineName + "</td><td>" + v.name + "<td>"
									+ v.nameNorms + "</td><td>" + inventoryType + "</td><td>" + startDate
									+ "</td><td>" + initial + "</td><td>" + adjustment + "</td>" +
									"<td>" + netWeight + "</td><td>" + realExpend + "</td><td>"
									+ parseFloat(v.storeValue).toFixed(2) + "</td><td>"
									+ maxCapacity + "</td><td>" + rate.toFixed(2) + "%</td><td>" + btn + "</td></tr>";
							} else if (index == '共享仓明细') {
								gStockHtml += "<tr><td>共享仓</td><td>" + v.name + "<td>"
									+ v.nameNorms + "</td><td>" + inventoryType + "</td><td>" + startDate
									+ "</td><td>" + initial + "</td><td>" + adjustment + "</td>" +
									"<td>" + netWeight + "</td><td>" + realExpend + "</td><td>"
									+ parseFloat(v.storeValue).toFixed(2) + "</td><td>"
									+ maxCapacity + "</td><td>" + rate.toFixed(2) + "%</td><td>" + btn + "</td></tr>";
							} else if (index == '堆仓明细') {
								dStockHtml += "<tr><td>堆仓</td><td>" + v.name + "<td>"
									+ v.nameNorms + "</td><td>" + inventoryType + "</td><td>" + startDate
									+ "</td><td>" + initial + "</td><td>" + adjustment + "</td>" +
									"<td>" + netWeight + "</td><td>" + realExpend + "</td><td>"
									+ parseFloat(v.storeValue).toFixed(2) + "</td><td>"
									+ maxCapacity + "</td><td>" + rate.toFixed(2) + "%</td><td>" + btn + "</td></tr>";
							}

						});
						var labelObj = {show: true, position: 'inside', valueAnimation: true,
							//      formatter:'{b}\n{c}'};
							formatter:function(param){
								if (param.value > 0) {
									var obj_ = seriesObject[param.name];
									var maxCapacity = obj_.maxCapacity / 1000;
									var rate = parseFloat((parseFloat(param.value) / parseFloat(maxCapacity)) * 100).toFixed(1);
									var showTip = param.name + '\n' + param.value + ' / ' + maxCapacity
										+ '(吨)\n余量占比:' + rate + '%';
									if (maxCapacity > 10000)
										showTip = param.name + '\n' + param.value + '(吨)';
									return showTip;
								}
								return '';
							}};
						if (index == '共享仓' || index == '堆仓') {
							yMaxArray = [{type: "value"}]
						}
						if (index.indexOf('明细') == -1) {
							var charObj = {
								title:{text:index + '库存信息',left:'center'},
								tooltip:{trigger:'axis',axisPointer:{type:'shadow',axisTick:{alignWithLabel:true}}},
								grid:{left:'3%',right:'4%',bottom:'3%',containLabel:true},
								yAxis:yMaxArray,
								xAxis: [{ type: 'category', data: xAxisArray}],
								series:[{name:'单位(吨)',type:'bar',barWidth:'60%',showBackground: true,
									barWidth:'60%',data:seriesArray,label:labelObj}]
							};
							chartList.push(charObj);
						}
					});
					// tabTitleHtml += '<li>明细</li>';
					stockHtml += '<div class="layui-tab-item">\n' +
						'<table class="layui-table chartList" lay-filter="table01">\n' +
						'<thead><tr><th>生产线</th><th>仓位</th><th>材料</th><td>类型</td><th>盘存时间</th><th>期初</th>' +
						'<th>调整值</th><th>购进</th><th>消耗</th><th>库存</th><th>容量</th><th>占比</th><th>操作</th></tr></thead>\n' +
						'<tbody class="tableList"></tbody></table></div>';
					stockHtml += '<div class="layui-tab-item">\n' +
						'<table class="layui-table chartList" lay-filter="table02">\n' +
						'<thead><tr><th>名称</th><th>仓位</th><th>材料</th><td>类型</td><th>盘存时间</th><th>期初</th>' +
						'<th>调整值</th><th>购进</th><th>消耗</th><th>库存</th><th>容量</th><th>占比</th><th>操作</th></tr></thead>\n' +
						'<tbody class="g-tableList"></tbody></table></div>';
					stockHtml += '<div class="layui-tab-item">\n' +
						'<table class="layui-table chartList" lay-filter="table03">\n' +
						'<thead><tr><th>名称</th><th>仓位</th><th>材料</th><td>类型</td><th>盘存时间</th><th>期初</th>' +
						'<th>调整值</th><th>购进</th><th>消耗</th><th>库存</th><th>容量</th><th>占比</th><th>操作</th></tr></thead>\n' +
						'<tbody class="d-tableList"></tbody></table></div>';

					/**标签头**/
					$(".stock-tab-title").empty().append(tabTitleHtml);
					$(".stock-content").empty().append(stockHtml);

					$(".chartList .tableList").empty().append(tStockHtml);
					$(".chartList .g-tableList").empty().append(gStockHtml);
					$(".chartList .d-tableList").empty().append(dStockHtml);
					replaceNull($(".chartList .tableList"));
					replaceNull($(".chartList .g-tableList"));
					replaceNull($(".chartList .d-tableList"));

					if (chartList != null) {
						var idx = 0;
						// console.log(arr)
						$.each(chartList, function (index, val) {
							var netChartDom = document.getElementById(arr[index]);
							var netChart = echarts.init(netChartDom);
							netChart.setOption(val);
							if (idx > 0)
								$("#" + arr[index]).hide();
							idx++;
							netChart.on('dblclick', function (params) {
								var name = params.name;
								var obj_ = seriesObject[params.name];
								// console.log(params)
								// console.log(obj_);
								if (name.indexOf('\n') != -1) {
									buildStore(obj_);
								} else {
									layer.msg('堆场请在堆场明细中查看详情或盘存');
								}
							});
						});
						// netOption = res.data.json;
						// netOption && netChart.setOption(netOption);
					}
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});

	}
	function buildStore(data) {
		$('.addModal').show();
		var isInsert = $('.isInsert').val();
		if (isInsert == 1)
			$('.store-save-item').show();
		else
			$('.store-save-item').hide();
		if (!isNull(data.code))
			$('.add-code').val(data.code);
		if (!isNull(data.lineName))
			$('.add-lineName').val(data.lineName);
		if (!isNull(data.name))
			$('.add-name').val(data.name);
		if (!isNull(data.nameNorms))
			$('.add-nameNorms').val(data.nameNorms);
		if (!isNull(data.startDate))
			$('.add-startDate').val(data.startDate);
		if (!isNull(data.initial))
			$('.add-initial').val(parseFloat(data.initial / 1000).toFixed(2));
		if (!isNull(data.netWeight))
			$('.add-netWeight').val(parseFloat(data.netWeight / 1000).toFixed(2));
		if (!isNull(data.realExpend))
			$('.add-realExpend').val(parseFloat(data.realExpend / 1000).toFixed(2));
		if (!isNull(data.dosage))
			$('.add-dosage').val(parseFloat(data.dosage / 1000).toFixed(2));
		if (!isNull(data.type)) {
			var type = data.type == 0 ? '筒仓' : '堆场'
			$('.add-type').val(type);
		}
		if (!isNull(data.historyType)) {//0:系统计算1:原材盘点2:仓位换料
			var historyType = '系统计算';
			if (data.historyType == 1)
				historyType = '原材盘点';
			else if (data.historyType == 2)
				historyType = '仓位换料';
			$('.add-historyType').val(historyType);
		}
		if (!isNull(data.storeValue))
			$('.add-storeValue').val(data.storeValue);
		if (!isNull(data.maxCapacity))
			$('.add-maxCapacity').val(parseFloat(data.maxCapacity / 1000).toFixed(2));
		$('.add-storeId').val(data.id);
	}
});
function refreshTimer(time) {//定时器刷新待办事项
	time--;
	if (time <= 0) {
		time = clockTime;
		clearTimeout(todoTimer);
		$(".search-btn").trigger("click");
		refreshTimer(time);
	} else {
		todoTimer = setTimeout('refreshTimer(' + time +')',1000);
	}
}